//
//  ImageMagickTools.m
//  tangyuanReader
//
//  Created by 王 强 on 13-8-5.
//  Copyright (c) 2013年 中文在线. All rights reserved.
//

#import "ImageMagickTools.h"
#import "MagickWand.h"
#import <ImageIO/ImageIO.h> // For CGImageDestination
#import <MobileCoreServices/MobileCoreServices.h> // For the UTI types constants

#define ThrowWandException(wand) { \
char * description; \
ExceptionType severity; \
\
description = MagickGetException(wand,&severity); \
(void) fprintf(stderr, "%s %s %lu %s\n", GetMagickModule(), description); \
description = (char *) MagickRelinquishMemory(description); \
exit(-1); \
}


@implementation ImageMagickTools

+(void)compress:(UIImage *)image path:(NSString *)path quality:(size_t)quality{
    
    //        CGImageRef srcCGImage = [thumbimg CGImage];
    //        NSData * srcData = (__bridge NSData *) CGDataProviderCopyData(CGImageGetDataProvider(srcCGImage));
    
    MagickWandGenesis();
    
    MagickBooleanType status=MagickFalse;
    
    MagickWand *localWand = NewMagickWand();
    
    NSData * dataObj = UIImagePNGRepresentation(image);
    MagickSetFormat(localWand, "png");
    status= MagickReadImageBlob(localWand, [dataObj bytes], [dataObj length]);
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}
    
    /*status=MagickResizeImage(localWand,  1024, 6000, UndefinedFilter, 1.0);
    //    status=MagickTransformImage(localWand, "0x0", "1024x6000");
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}*/
    
    status=MagickStripImage(localWand);
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}
 /*
    status=MagickEnhanceImage(localWand);
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}
    
    status=MagickDespeckleImage(localWand);
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}
  */
        
    size_t t=quality;
    status=MagickSetImageCompressionQuality(localWand,t);
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}
    
    MagickSetFormat(localWand, "jpg");    
    const char * filename= [path cStringUsingEncoding:NSUTF8StringEncoding];
	status=MagickWriteImage(localWand, filename);
    if (status == MagickFalse) {
		ThrowWandException(localWand);
	}
    
    DestroyMagickWand(localWand);
    MagickWandTerminus();
}

+(void)compress:(UIImage *)image path:(NSString *)path{
    [self compress:image path:path quality:70];
}

+(void)newCompress:(UIImage *)image path:(NSString *)path quality:(CGFloat)quality{

    [self image:image saveToURL:[NSURL fileURLWithPath:path] uti:kUTTypeJPEG quality:quality backgroundFillColor:nil];

}

+(BOOL)image:(UIImage *)image saveToURL:(NSURL*)url uti:(CFStringRef)uti quality:(CGFloat)quality backgroundFillColor:(UIColor*)fillColor
{
    if (!url)
        return NO;
    
    if (!uti)
        uti = kUTTypePNG;
    
    CGImageDestinationRef dest = CGImageDestinationCreateWithURL((__bridge CFURLRef)url, uti, 1, NULL);
    if (!dest)
        return NO;
    
    /// Set the options, 1 -> lossless
    CFMutableDictionaryRef options = CFDictionaryCreateMutable(kCFAllocatorDefault, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    if (!options)
    {
        CFRelease(dest);
        return NO;
    }
    CFDictionaryAddValue(options, kCGImageDestinationLossyCompressionQuality, (__bridge CFNumberRef)[NSNumber numberWithFloat:quality]); // No compression
    if (fillColor)
        CFDictionaryAddValue(options, kCGImageDestinationBackgroundColor, fillColor.CGColor);
    
    /// Add the image
    CGImageDestinationAddImage(dest, image.CGImage, (CFDictionaryRef)options);
    
    /// Write it to the destination
    const bool success = CGImageDestinationFinalize(dest);
    
    /// Cleanup
    CFRelease(options);
    CFRelease(dest);
    
    return success;
}
+(void)oldCompress:(UIImage *)image path:(NSString *)path quality:(CGFloat)quality{
    
    NSData *_data = UIImageJPEGRepresentation(image, quality);
    [[NSFileManager defaultManager] createFileAtPath:path contents:_data attributes:nil];

    
}




@end
